package com.bestdo.returndata;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerByte {
	private static ExecutorService es = Executors.newFixedThreadPool(2);
	public static void main(String[] args){
		
		args = new String[]{"8088"};
		
		int port = 0;
		if(args == null || args.length !=1){
			System.err.println("***请输入正确的port参数！***");
			System.exit(0);
		}
		try{
			port = Integer.parseInt(args[0]);
		}catch(Exception e){
			System.err.println("***请输入正确的port参数！***");
			System.exit(0);
		}
		ServerSocket ss = null;
		try{
			 ss = new ServerSocket(port);
			 ss.setReuseAddress(true);
			 System.out.println("***服务启动成功！***");
			while(true){
				Socket s = ss.accept();
				es.execute(new DealDataByte(s));
			}
		}catch(Exception e){
			e.printStackTrace();
			System.err.println("***数据处理异常，服务器退出！***");
			System.exit(0);
		}finally{
			try {
				ss.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

class DealDataByte extends Thread{
	private Socket s;
	public DealDataByte(Socket s) {
		this.s = s;
	}
	@Override
	public void run() {
		try(
				InputStream is = s.getInputStream();
				OutputStream os = s.getOutputStream();
				Socket ss = this.s;
			){
            String strs = new String(ClientByte.read(is));
            System.out.println("***data:["+System.currentTimeMillis()+"]"+strs);
            os.write(ClientByte.deal(strs.getBytes()));
            os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
